<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
       <!-- <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" clearable placeholder="请选择">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="状态">
          <el-select v-model="listQuery.status" placeholder="请选择" style="width: 90px;">
            <el-option
              v-for="item in status_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item> -->

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:parkMch:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <el-table-column align="center" label="商户ID" prop="mchId"/>
      <el-table-column align="center" label="商户名称" prop="name"/>

      <!-- <el-table-column align="center" label="商户类型" prop="type">
        <template slot-scope="scope">
          <el-tag>{{ getStatus(scope.row.type) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="所属组织" prop="organizationNameStr" show-overflow-tooltip/>

      <el-table-column align="center" label="添加时间" prop="createTime"/>

      <el-table-column align="center" label="渠道" prop="channel">
        <template slot-scope="{row}">
          <dict-tag  :options="dict.type.ELoginChannel" :value="row.channel"/>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:parkMch:update']"
            type="primary"
            size="small"
            @click="startEditMch(scope.row)">编辑</el-button>
          <!-- <el-button
            v-hasPermi="['admin:parkMch:delete']"
            type="primary"
            size="small"
            @click="deleteMch(scope.row.name, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加微信商户':'修改微信商户'" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm" :inline="true" :rules="formRules" :model="dialogForm" align="center" label-width="120px">
        <!-- <el-form-item label=" 机构  " prop="departmentId">
          <el-select v-model="dialogForm.departmentId" :disabled="dialogType == 2" placeholder="请选择" @change="selectDepartmentId">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item> -->
				<el-form-item label=" 组织  " prop="orgIdList">
				  <el-select v-model="dialogForm.orgIdList" multiple placeholder="请选择" >
				    <el-option
				      v-for="item in orangeList"
				      :key="item.id"
				      :label="item.name"
				      :value="item.id"/>
				  </el-select>
				</el-form-item>

        <el-form-item label=" 商户名称  " prop="name">
          <el-input v-model="dialogForm.name" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 商户id  " prop="mchId">
          <el-input v-model="dialogForm.mchId" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-select v-model="dialogForm.channel" placeholder="请选择渠道" style="max-width: 260px;">
            <el-option
              v-for="item in ELoginChannel"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"/>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label=" 商户密钥  ">-->
        <!--          <el-input v-model="dialogForm.secret" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label=" 商户公钥  " prop="publicKey">
          <el-input v-model="dialogForm.publicKey" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 商户私钥  " prop="privateKey">
          <el-input v-model="dialogForm.privateKey" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 商户密钥  " prop="secret">
          <el-input v-model="dialogForm.secret" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
/* eslint-disable eqeqeq */

import { fetchList, deleteParkMch, createParkMch, updateParkMch,parkMchDetail } from '@/api/parkMch'
// eslint-disable-next-line no-unused-vars
import { listOrgs } from '@/api/system/organization'
import { selectList } from '@/api/passway'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getData, } from '@/api/system/dictionary'
export default {
  name: 'Mch',
  components: { Pagination },
  dicts:['ELoginChannel'],
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      status_options: [{
        value: '',
        label: '全部'
      }, {
        value: '1',
        label: '启用'
      }, {
        value: '2',
        label: '停用'
      }],
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      departmentList: [],
      parkList: [],
      allParkList: [],
      passwayList: [],
      qrcodeDialogVisible: false,
      formRules: {
        name: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
        mchId: [{ required: true, message: '请输入商户ID', trigger: 'blur' }],
        publicKey: [{ required: true, message: '请输入商户公钥', trigger: 'blur' }],
        privateKey: [{ required: true, message: '请输入商户私钥', trigger: 'blur' }],
        secret: [{ required: true, message: '请输入商户密钥', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择机构名称', validator: this.checkSelected, trigger: 'change' }],
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        channel: [{ required: true, message: '请选择渠道', validator: this.checkSelected, trigger: 'change' }],
      },
			orangeList:[],//组织数据
      ELoginChannel:[],
    }
  },
  created() {
    this.getDepartmentList()
    this.getList()
  },
  methods: {
    async getData(){
      let res = await getData('ELoginChannel')
      let data = res.data || []
      this.ELoginChannel = data.filter(item=>item.label.includes('微信'))
    },
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId})
      return res.data || []
    },
    async listOrgs(){//根据机构获取组织
      let res = await listOrgs({})
			let list = res.data || []
			this.orangeList = [...list]
		},
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        console.log('response', response)
        let data = response.data || {}
				let list = data.list || []
        this.list = list.map(item=>{
					let orgList = item.orgList || []
          let organizationNameList = item.organizationNameList || []
					return {
						...item,
						orgIdList:orgList.map(item=>item.id),
            organizationNameStr:organizationNameList.toString(),
					}
				})
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getStatus(status) {
      if (status == 1) {
        return '微信公众号'
      }
      return '支付宝'
    },
    getType(type) {
      if (type == 1) {
        return '微信支付'
      }
      return '支付宝'
    },
    deleteMch(name, parkId) {
      this.$confirm(`您确定删除商户：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteParkMch({ 'id': parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.dialogForm = {}
      this.dialogFormVisible = true
      this.dialogType = 1
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
			this.orangeList = []
      this.getDepartmentList()
      this.listOrgs()
      this.getData()
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
					this.dialogForm.type = 1
          if (this.dialogType == 1) {
            createParkMch(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updateParkMch(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    reset() {
      this.dialogForm = {};
      this.resetForm("dialogForm");
    },
    startEditMch(row) {
      this.reset();
      parkMchDetail(row.id).then(async response => {
        this.dialogFormVisible = true
        this.dialogType = 2
        let data = response.data || {}
        this.dialogForm = {
          ...data,
          orgIdList:data.organizationIds || [],
        }
        this.parkList = []
        this.orangeList = []
        this.$nextTick(() => {
          this.$refs.dialogForm.clearValidate()
        })
        this.listOrgs()
        // this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
        this.getDepartmentList()
        this.getData()
      });
    },
    async selectDepartmentId(event) {
      this.parkList = []
			this.orangeList = []
			let dialogForm = {...this.dialogForm}
			// dialogForm.orgIdList = []
			this.dialogForm = {...dialogForm}
			this.listOrgs()
      this.parkList = await this.getListAuthPark(event)
    }

  }
}
</script>
